package com.hj.auth.service;

import com.alibaba.fastjson.JSON;
import com.hj.auth.model.request.BaseRequest;
import org.bouncycastle.tsp.TSPUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${server.port}")
    private int port;

    @Autowired
    private RestTemplate restTemplate;

    public String applyToken(MultiValueMap<String, String> body, BaseRequest request) {
        String authUrl = "http://localhost:"+port+"/oauth/token";
        //请求的内容分两部分
        //1、header信息，包括了http basic认证信息
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        String httpBasic = httpBasic(request.getClientId(), request.getClientSecret());
        headers.add("Authorization", httpBasic);
        HttpEntity<MultiValueMap<String, String>> multiValueMapHttpEntity = new
                HttpEntity<MultiValueMap<String, String>>(body, headers);
        //指定 restTemplate当遇到400或401响应时候也不要抛出异常，也要正常返回值
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                //当响应的值为400或401时候也要正常响应，不要抛出异常
                if(response.getRawStatusCode()!=400 && response.getRawStatusCode()!=401){
                    super.handleError(response);
                }
            }
        });
        //远程调用申请令牌
        ResponseEntity<Map> exchange = restTemplate.exchange(authUrl, HttpMethod.POST,
                multiValueMapHttpEntity,Map.class);
        Map result = exchange.getBody();
        if(result!=null && result.size()>0 && result.get("access_token")!=null){
            System.out.println("{");
            System.out.println("access_token:"+"\""+result.get("access_token")+"\"");
            System.out.println("refresh_token:"+"\""+result.get("refresh_token")+"\"");
            System.out.println("jti:"+"\""+result.get("jti")+"\"");
            System.out.println("}");
        }
        return null;
    }

    /**
     * 将客户端ID和客户端密码使用base64编码
     * @param clientId
     * @param clientSecret
     * @return
     */
    private String httpBasic(String clientId,String clientSecret){
        //将客户端id和客户端密码拼接，按“客户端id:客户端密码”
        String string = clientId+":"+clientSecret;
        //进行base64编码
        byte[] encode = Base64Utils.encode(string.getBytes());
        return "Basic "+new String(encode);
    }

    /**
     * 存储token
     * @param accessToken
     * @param content
     * @return
     */
    private boolean saveToken(String accessToken,String content){
//        String key = SsoConstants.TOKEN_STORE_PREFIX + accessToken;
//        stringRedisTemplate.boundValueOps(key).set(content,constantConfig.getExpireTime(), TimeUnit.SECONDS);
//        Long expire = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
//        return expire > -2 ;
        return false;
    }
}
